<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>taobao</title>
    <script src="lib/jquery.js"></script>
    <script src="lib/template-web.js"></script>
    <script src="lib/axios.js"></script>
    <link rel="stylesheet" href="css/tb_search.css">
</head>
<body>
<div class="top" style="background-color: #4ad2aa;">
    <img class="top-img" src="https://ossgw.alicdn.com/alp/1616702408152-1200-90.png" alt="">
</div>
<div class="search-main">
    <img class="search-img" src="https://ossgw.alicdn.com/alp/1572809375526-200-76.png">
    <div class="search-body">
        <span class="search-input">
            <input type="text" class="ipt-txt">
            <button class="top-btn">搜索</button>
        </span>
        <div id="suggest-list"></div>
    </div>
</div>
<script type="text/html" id="tb-template">
    {{each result}}
    <div class="suggest-item">{{$value[0]}}</div>
    {{/each}}
</script>

<script>
    $(function () {

            var timer = null;

            var cacheObj = {};

            function debouceSezrch(kw) {
                timer = setTimeout(() => {
                    getSuggestList(kw)
                }, 500)
            }

            $('.ipt-txt').on('keyup', function () {
                clearTimeout(timer);
                var keywords = $('.ipt-txt').val().trim();
                if (keywords.length <= 0) {
                    return $('#suggest-list').empty().hide()
                }
                if (cacheObj[keywords]){
                    return renderSuggestList(cacheObj[keywords])
                }
                debouceSezrch(keywords)
            })

            function getSuggestList(kw) {
                $.ajax({
                    url: 'https://suggest.taobao.com/sug?q=' + kw,
                    dataType: 'jsonp',
                    success: function (res) {
                        renderSuggestList(res)
                    }
                })
            }

            function renderSuggestList(res) {
                if (res.result.length <= 0) {
                    return $('#suggest-list').empty().hide()
                }
                var htmlStr = template('tb-template', res)
                $('#suggest-list').html(htmlStr).show()
                var k = $('.ipt-txt').val().trim();
                cacheObj[k] = res;
            }

            $('.top-btn').on('click', function () {
                window.open('https://ai.taobao.com/search/index.htm?spm=a231o.13503973.search.1&key=' + $('.ipt-txt').val().trim(), '_target')
            })
        }
    )
</script>
</body>
</html>
